<template>
  <a-form :form="form" class="ResumeUpdate">
    <div class="image">
      <a-spin v-if="!templates"/>
      <template v-else>
        <p @click="() => avatarUpShow = true">
          <img :src="photoAddress || require(`@/assets/images/header.png`)" />
          <my-upload field="img"  @crop-success='cropSuccess' v-if="avatarUpShow" v-model="avatarUpShow" :width="100" :height="100" img-format="jpg" :noSquare="true"></my-upload>
        </p>
        <div>{{$t('candidateApplication.click_upload_header')}}</div>
      </template>
    </div>
    <template v-for="(template, i) in templates">
      <h4 :key="template.path">
        <i :class="`iconfont ${icons[template.path] || 'icon-zidingyilie'} clo`"></i>
        <span>{{ template.title }}</span>
        <!--  -->
      </h4>
      <resume-update-div :key="i" :template="template" :group="formDataTmp[template.path]" @del="del">
        <a-row :gutter="24" slot="editContent" slot-scope="{fields, index}">
          <a-col v-for="(record, j) in fields" :key="j" class="formCol" :span="record.type === 'TEXT_AREA' || record.type === 'RICH_TEXTAREA' ? 24 : 12" >
            <a-form-item>
              <template slot="label" class="disposeLabel">
                <a-tooltip>
                  <template slot='title'>
                    {{ record.title }}
                  </template>
                  {{ record.title }}
                  <!-- {{record.visible}}.filter(val => val.visible)
                  {{template.type === 'LIST' ? decId(template.path, index, record.path) : record.fullPath}} -->
                </a-tooltip>
              </template>
              <!-- :is="record.fullPath === 'basic.mobile' ? 'MobileInternational' : record.type" -->
              <component
                ref="forms"
                v-decorator="[template.type === 'LIST' ? decId(template.path, index, record.path) : record.fullPath, {rules: [{ required: record.required, message: $t('common.pleaseEnter') + record.title }]}]"
                :is="record.fullPath === 'basic.mobile' ? 'MobileInternational' : record.type"
                :defaultPickerValue="record.path === 'graduationTime'?moment('2015/07/01'): ''"
                :keys="record.key"
                :placeholders="record.displayName"
                :url='record.url'
                :values='record.enums'
                :isSoFar="record.path === 'endDate'"
                :isDisabled="record.disabled || (isEdit && (record.fullPath === 'basic.name' || record.fullPath === 'basic.email' || record.fullPath === 'basic.mobile'))" />
            </a-form-item>
          </a-col>
        </a-row>
      </resume-update-div>
      <p :key="template.path+i" class="addMoudle">
        <span v-if="template.type === 'LIST'" @click="addMoudle(template)"><a-icon type="plus" />{{$t('common.increase')}}{{template.title}}</span>
      </p>
    </template>
  </a-form>
</template>
<script>
import loGet from 'lodash.get'
import loSet from 'lodash.set'
import moment from 'moment'
import myUpload from 'vue-image-crop-upload'
import Editor from '@/components/Editor/Editor'
import TEXT_FIELD from '@/components/formComponents/TextField/TextField'
import MOBILE from '@/components/formComponents/Phone/Phone'
import EMAIL from '@/components/formComponents/Email/Email'
import RADIO_GROUP from '@/components/formComponents/RadioGroup/RadioGroup'
import CHECKBOX_GROUP from '@/components/formComponents/Checkbox/Checkbox'
import DATE from '@/components/formComponents/FormattingDate/FormattingDate'
import INT from '@/components/formComponents/Int/Int'
import TEXT_AREA from '@/components/formComponents/TEXT_AREA/TEXT_AREA'
import SELECT from '@/components/formComponents/Select/Select'
import DEPARTMENT from '@/components/formComponents/Department/Department'
import SELECT_URL from '@/components/formComponents/SelectUrl/SelectUrl'
import RICH_TEXTAREA from '@/components/formComponents/RichTextarea/RichTextarea'
import JOB_TYPE from '@/components/formComponents/JobType/JobType'
import CHECKBOX from '@/components/formComponents/jobTypeCheckbox/jobTypeCheckbox'
import ResumeUpdateDiv from '@/components/resume/ResumeUpdateDiv'
import SCHOOLSELECTOR from '@/components/formComponents/schoolSelector/schoolSelector'
import MobileInternational from '@/components/formComponents/MobileInternational/MobileInternational'
import LOCATION from '@/components/formComponents/Location/city'
import { findTemplate, saveResume, photoUpload } from '@/api/resume'
let scroll = true
export default {
  name: 'ResumeUpdate',
  props: [ 'formData', 'enterpriseId', 'positionId', 'resumeId', 'fileData', 'id', 'isEdit', 'positionInfo', 'isPending' ],
  components: {
    SCHOOLSELECTOR,
    LOCATION,
    Editor,
    TEXT_FIELD,
    MOBILE,
    EMAIL,
    RADIO_GROUP,
    CHECKBOX_GROUP,
    DATE,
    INT,
    TEXT_AREA,
    SELECT,
    DEPARTMENT,
    SELECT_URL,
    RICH_TEXTAREA,
    JOB_TYPE,
    CHECKBOX,
    ResumeUpdateDiv,
    MobileInternational,
    myUpload
  },
  data () {
    return {
      loGet,
      loSet,
      moment,
      icons: {
        'section_eb64e7fa5d9f47618e9d9a9df635b3ab': 'icon-zidingyilie',
        'jobObjective': 'icon-hulianwang',
        'workExp': 'icon-zhiwei',
        'eduExp': 'icon-chengshijinglixianxing',
        'projectExp': 'icon-zidingyilie',
        'selfCommSec': 'icon-user'
      },
      requireList: [],
      templates: null,
      avatarUpShow: false,
      photoAddress: '',
      form: this.$form.createForm(this),
      formDataTmp: {}
    }
  },
  created () {
    this.formDataTmp = this.formData ? JSON.parse(JSON.stringify(this.formData.info)) : {}
    this.getTemplate()
    this.photoAddress = this.formDataTmp.basic && this.formDataTmp.basic.photoAddress
  },
  watch: {
    formData: {
      handler (newValue, oldValue) {
        if (newValue && JSON.stringify(newValue) !== '{}') {
          this.form.resetFields()
          this.formDataTmp = JSON.parse(JSON.stringify(newValue)) || {}
          this.form.setFieldsValue(this.formDataTmp)
          this.photoAddress = this.formDataTmp.basic && this.formDataTmp.basic.photoAddress
        }
      },
      deep: true,
      immediate: false
    }
  },
  methods: {
    async sendPhoto (imgData) {
      let params = {
        // id: this.id,
        resumeId: this.resumeId,
        isRPO: this.positionInfo.isRPO || 'N',
        image: imgData
      }
      if (this.isPending) {
        params.analyzerRecordId = this.positionInfo.id
      } else {
        params.id = this.id
      }
      let res = await photoUpload(params)
      if (res.code === 200) {
        this.photoAddress = res.photoAddress
        // this.$message.error(res.message)
      } else {
        this.$message.error(res.message)
      }
    },
    cropSuccess (imgData) {
      this.sendPhoto(imgData)
    },
    arrangeData (values) { // 整理上送数据
      this.templates.forEach(template => {
        template.fields && template.fields.forEach(item => {
          if (item.enums) {
            // let arrStr = null
            item.enums && item.enums.some(v => {
              if (template.type === 'LIST') {
                values[template.path] && values[template.path].forEach(val => {
                  if (this.loGet(val, item.path) && v.id === (this.loGet(val, item.path) ? this.loGet(val, item.path).id : '')) {
                    this.loSet(val, item.path, v.id)
                    return true
                  }
                })
              } else {
                if (this.loGet(values, item.fullPath) && v.id === (this.loGet(values, item.fullPath) ? this.loGet(values, item.fullPath).id : '')) {
                  this.loSet(values, item.fullPath, v.id)
                  return true
                }
              }
            })
          }
        })
      })
      return values
    },
    getError (data) {
      for (let item in data) {
        // 如果是对象类型，则继续循环
        if (item === 'errors' && document.getElementById(`${data[item][0].field}`) && scroll) {
          document.getElementById(`${data[item][0].field}`).closest('.formCol').scrollIntoView(true)
          scroll = false
          break
        } else {
          this.getError(data[item])
        }
      }
    },
    sendData () { // 上送数据传递到父组件
      return new Promise((resolve, reject) => {
        this.form.validateFields(async (error, values) => {
          if (!error) {
            let data = this.arrangeData(values)
            if (!data.basic) {
              data.basic = {}
            }
            data.basic.photoAddress = this.photoAddress
            let params = {
              ...this.fileData,
              ...data.basic,
              // enterpriseId: this.enterpriseId,
              id: this.id,
              info: data,
              positionId: this.positionId,
              positionName: this.positionInfo.name || this.formData.positionName
              // isRPO: this.positionInfo.isRPO || 'N',
              // resumeId: this.resumeId
            }
            // if (this.isPending) {
            //   params.analyzerRecordId = this.positionInfo.id
            // } else {
            //   params.id = this.id
            // }
            let res = await saveResume(params)
            if (res.code === 200) {
              // this.resumeId = res.resumeId
              // 处理数据
              resolve({ resumeId: res.code, values })
            } else {
              this.$message.error(res.message)
            }
          } else {
            scroll = true
            this.getError(error)
            reject(error)
          }
        })
      }).catch((e) => {
        console.log(e)
      })
    },
    del ({ template, index }) {
      let path = template.path
      // 获取表单数据
      let values = this.form.getFieldValue(path)
      if (values) {
        values.splice(index, 1)
      }
      // 设置删除后数据
      this.$set(this.formDataTmp, path, values)
      let obj = {}
      obj[path] = values
      this.$nextTick(() => {
        this.form.setFieldsValue(obj)
      })
    },
    addMoudle (template) {
      // 整理表单需要添加的列表数据
      let tmpField = {}
      template.fields.forEach((item) => {
        tmpField[item.path] = ''
      })
      let path = template.path
      // 获取表单数据
      let values = this.form.getFieldValue(path) || []
      values.push(tmpField)
      // 添加新增数据
      this.$set(this.formDataTmp, path, values)
      let obj = {}
      obj[path] = values
      this.$nextTick(() => {
        this.form.setFieldsValue(obj)
      })
    },
    decId (template, index, record) {
      return `${template}[${index}].${record}`
    },
    arrange () { // 组装页面需展示的单选、下拉等数据
      let that = this
      that.templates.forEach((template) => {
        template.fields.forEach(item => {
          if (item.enums) {
            item.enums.some(v => {
              if (template.type === 'LIST') {
                that.formDataTmp[template.path] && that.formDataTmp[template.path].forEach(val => {
                  // 设置list数据
                  if (this.loGet(val, item.path) && this.loGet(val, item.path).id === v.id) {
                    this.loSet(val, item.path, v)
                    return true
                  }
                })
              } else {
                // 设置数据数据，将v.id取出来
                if (this.loGet(that.formDataTmp, item.fullPath) && this.loGet(that.formDataTmp, item.fullPath).id === v.id) {
                  this.loSet(that.formDataTmp, item.fullPath, v)
                  return true
                }
              }
            })
          }
        })
      })
    },
    async getTemplate () {
      let res = await findTemplate({ enterpriseId: this.enterpriseId, positionId: this.positionId, isRPO: this.positionInfo.isRPO || 'N' })
      if (res.code === 200) {
        // 处理表单数据并传递给页面
        this.templates = res.data.fields
        this.$nextTick(() => {
          this.arrange()
          this.form.setFieldsValue(this.formDataTmp)
        })
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '../../styles/var.styl'
.ResumeUpdate
  .image
    display flex
    justify-content center
    align-items center
    flex-direction column
    >p
      background var(--light-grey)
      border-radius 50%
      overflow hidden
      border 1px solid borderColor
      margin-bottom 3px
      img
        width 100px
        height 100px
  h4
    font-weight bold
    font-size 16px
    display flex
    align-items center
    padding-bottom 8px
    margin-bottom 8px
    margin-top 8px
    border-bottom 1px dashed borderColor
    color var(--blue-500)
    i.clo
      font-weight normal
      margin-right 3px
  .addMoudle
    padding 12px
    text-align center
    >span
      display inline-block
      font-size 14px
      font-weight normal
      margin-left 12px
      width 350px
      padding 6px 0
      cursor pointer
      // border 1px dashed borderColor
      // &:hover
      color hoverBlue
      border 1px dashed hoverBlue
      i
        margin-right 3px
  :global(.ant-form-item-label)
    line-height 25px
</style>
